package com.qf.shiro;

import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsAdminService;
import com.qf.service.DtsRoleService;
import com.qf.service.PermissionService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author 邢式瑞
 * @version 1.0
 * @project E-commercebackGroundManagementSystem
 * @date 2022/9/20 14:09
 */
public class AdminAuthorizingRealm extends AuthorizingRealm  {
    @Autowired
    private DtsAdminService dtsAdminService;
    @Autowired
    private DtsRoleService dtsRoleService;
    @Autowired
    private PermissionService permissionService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        if (principals == null) {
            throw new AuthorizationException("[AdminAuthorizingRealm类, doGetAuthorizationInfo方法] 授权用户不能为空!");
        }
        //1. 获取认证后的用户对象
        DtsAdmin admin = (DtsAdmin) getAvailablePrincipal(principals);
        //2. 从用户对象中获取, 用户拥有的角色数组
        Integer[] roleIds = admin.getRoleIds();
        //3. 根据角色数组到数据库中查询到对应的用户名称集合
        Set<String> roles = dtsRoleService.queryByIds(roleIds);

        //4. 根据角色数组到数据库中查询到对应的权限字符串集合
        Set<String> permissions = permissionService.queryByRoleIds(roleIds);
        //5. 创建shiro框架的权限对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //6. 这个用户拥有的角色名称加入到shiro框架
        info.setRoles(roles);
        //7. 这个用户拥有的权限字符串集合加入到shiro框架
        info.setStringPermissions(permissions);
        //8. 返回权限对象
        return info;
    }



    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
      UsernamePasswordToken usernamePasswordToken=   (UsernamePasswordToken)authenticationToken;
        String username = usernamePasswordToken.getUsername();
        char[] pwd = usernamePasswordToken.getPassword();
        String password = new String(pwd);
     DtsAdmin dtsAdmin = dtsAdminService.findDtsAdminByUsername(username);
     if(dtsAdmin==null){
         throw new UnknownAccountException();
     }
 if(!new BCryptPasswordEncoder().matches(password,dtsAdmin.getPassword())){

     throw  new IncorrectCredentialsException();
 }
        if(dtsAdmin.getDeleted()){

     throw new LockedAccountException();
 }

        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(dtsAdmin, password, this.getName());

 return  authenticationInfo;
    }
}
